#include "client_server_functions.h"

/**
 * Creates the server socket and listen to incoming connections
 */
void createServer(int *socketS, const int port) {

	struct sockaddr_in server;

	/* open socket */
	if ((*socketS = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		quit("socket() failed", EXIT_FAILURE);
	}

	int reuse = 1;
	
	setsockopt(*socketS, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof (reuse));
	
	/* setup server's IP and port */
	memset(&server, 0, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = INADDR_ANY;

	/* bind the socket */
	if (bind(*socketS, (struct sockaddr*)&server, sizeof(server)) == -1) {
		quit("bind() failed", EXIT_FAILURE);
	}

	/* wait for connection */
	if (listen(*socketS, 3) == -1) {
		quit("listen() failed.", EXIT_FAILURE);
	}
}

/**
 * Accepts the clients connections
 */
void acceptClients(int socketS, int *socketToC, int nOfConnections) {

	int i = 0;

	for(i = 0; i < nOfConnections; i++) {
		fprintf(stderr, "accepting %d\n", i+1);
		/* accept a client */
		if ((socketToC[i] = accept(socketS, NULL, NULL)) < 0) {
			quit("accept() failed", EXIT_FAILURE);
		}
		fprintf(stderr, "accepted %d\n", i+1);
	}
}

/**
 * Connects to the server
 */
void connectToServer(int *socketC, const char *serverIp, const int port) {

	struct sockaddr_in server;

	/* create socket */
	if ((*socketC = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		quit("socket() failed", EXIT_FAILURE);
	}

	/* setup server parameters */
	memset(&server, 0, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = inet_addr(serverIp);

	/* connect to server 
	if (connect(*socketC, (struct sockaddr*)&server, sizeof(server)) < 0) {
		quit("connect() failed.", 1);
	}
	*/
	
	/* connect to server */
	while (connect(*socketC, (struct sockaddr*)&server, sizeof(server)) < 0) {
	}

}

/**
 * Provides a way to exit nicely from the system
 */
void quit(char* msg, int returnValue) {
	if (msg == NULL) {
		fprintf(stderr, "quit message == NULL");
	} else {
		fprintf(stderr, "%s",msg);
	}
	fprintf(stderr, "\n");
	
	if (socketAsServer) close(socketAsServer);
	if (socketAsClient) close(socketAsClient);
	if (socketToClient[0]) close(socketToClient[0]);
	if (socketToClient[1]) close(socketToClient[1]);

	exit(returnValue);
}
